package com.project.market.controller;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/wx/storage/fetch/*")
public class WxStorageController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String requestURI = req.getRequestURI();
        String fileName = requestURI.replace(req.getContextPath()+"/wx/storage/fetch", "");
        File file = new File("D:/app/" + fileName);
        if(file.exists()&& file.isFile()){
            ServletOutputStream outputStream = resp.getOutputStream();
            FileInputStream inputStream = new FileInputStream(file);
            int length = 0;
            byte[] bytes = new byte[1024];
            while ((length = inputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,length);
            }
            inputStream.close();
            outputStream.close();
            return;
        }
        resp.setStatus(404);
    }
}
